package com.ics.atable.chat.log;

import org.springframework.web.reactive.function.client.ClientResponse;
import org.springframework.web.reactive.function.client.ExchangeFilterFunction;
import reactor.core.publisher.Mono;

public class WebClientLoggingFilter {

    public static ExchangeFilterFunction logRequest() {
        return ExchangeFilterFunction.ofRequestProcessor(request -> {
            System.out.println(">>> " + request.method() + " " + request.url());

            // 这里 request.body() 是不可直接打印的
            // 建议在构造请求对象时，自己用 ObjectMapper 转 JSON 打出来
            request.headers().forEach((name, values) ->
                    values.forEach(value -> System.out.println(name + ": " + value)));

            return Mono.just(request);
        });
    }

    public static ExchangeFilterFunction logResponse() {
        return ExchangeFilterFunction.ofResponseProcessor(response -> {
            System.out.println("<<< " + response.statusCode());

            // 打印响应体
            return response.bodyToMono(String.class)
                    .flatMap(body -> {
                        System.out.println("<<< Response Body: " + body);
                        // 为了不消费响应流，需要重新构造一个响应返回
                        return Mono.just(ClientResponse.from(response).body(body).build());
                    });
        });
    }
}
